package com.lcq.gulimall.authsever.utils;

import com.lcq.gulimall.authsever.constant.RegConstant;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class AuthCodeUtils {
    public static String getSaveKey(String phone){
        return RegConstant.AUTH_CODE_SAVE_PREFIX+phone;
    }
    public static String getSaveVal(StringRedisTemplate redisTemplate, String phone){
        String key = getSaveKey(phone);
        return redisTemplate.opsForValue().get(key);
    }

    public static String getSaveCode(StringRedisTemplate redisTemplate, String phone){
        String val = getSaveVal(redisTemplate, phone);
        if(StringUtils.isNotBlank(val)){
            String[] valSplit = val.split("_");
            if(valSplit.length==2){
                return valSplit[0];
            }
        }
        return "";
    }

    public static Long getSaveTime(StringRedisTemplate redisTemplate, String phone){
        String val = getSaveVal(redisTemplate, phone);
        if(StringUtils.isNotBlank(val)){
            String[] valSplit = val.split("_");
            if(valSplit.length==2){
                return Long.parseLong(valSplit[1]);
            }
        }
        return 0L;
    }

    public static String createCode(){
        return UUID.randomUUID().toString().substring(0,5);
    }

    public static void saveCode(StringRedisTemplate redisTemplate,String phone,String code){
        String key = getSaveKey(phone);
        redisTemplate.opsForValue().set(key, code+"_"+System.currentTimeMillis(),5, TimeUnit.MINUTES);
    }
}
